//
//  FYFPhotoBrowser.m
//  FYFPhotoBrowser
//
//  Created by fuyoufang on 16/5/16.
//  Copyright © 2016年 深圳－真二网. All rights reserved.
//

#import "FYFPhotoBrowser.h"
#import <Masonry.h>
#import <SDImageCache.h>
#import <UIImageView+WebCache.h>

#define ImageViewMargin 10

#define AnimateWithDuration 1

@interface FYFPhotoBrowser () <UIScrollViewDelegate>

@property (nonatomic, weak) UIScrollView *scrollView;
/** 当前展示的 index */
@property (nonatomic, assign) NSInteger currentIndex;
@property (nonatomic, assign) BOOL statusBarHidden;

@property (nonatomic, assign) BOOL isViewTransition;
@end

@implementation FYFPhotoBrowser

#pragma mark - setter
- (void)setDelegate:(id<FYFPhotoBrowserDelegate>)delegate {
    _delegate = delegate;
    
    //[self setupScrollViewData];
}

#pragma mark - 系统方法

- (instancetype)initWithDelegate:(id<FYFPhotoBrowserDelegate>)delegate
                    currentIndex:(NSInteger)currentIndex beginningImageView:(UIImageView *)beginningImageView {
    if (self = [self init]) {
        _delegate = delegate;
        _currentIndex = currentIndex;
        _beginningImageView = beginningImageView;
    }
    return self;
}

- (instancetype)init {
    if (self = [super init]) {
        [[SDImageCache sharedImageCache] cleanDisk];
        [[SDImageCache sharedImageCache] clearDisk];
        self.view.backgroundColor = [UIColor clearColor];
        _statusBarHidden = NO;
        _isViewTransition = NO;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    UIView *beginningSuperView = self.beginningImageView.superview;
    CGRect beginningImageViewFrame = [beginningSuperView convertRect:self.beginningImageView.frame toView:self.view];
    
    
    UIImageView *tempImageView = [[UIImageView alloc] initWithFrame:beginningImageViewFrame];
    [self.view addSubview:tempImageView];
    
    UIImage *beginningOriginalImage = [self originalImageAtIndex:self.currentIndex];
    if (beginningOriginalImage) {
        tempImageView.image = beginningOriginalImage;
        CGRect targetImageViewFrame = [self getImageShowFrame:beginningOriginalImage mainScreenSize:[UIScreen mainScreen].bounds.size];
        [UIView animateWithDuration:AnimateWithDuration animations:^{
            tempImageView.frame = targetImageViewFrame;
            
        } completion:^(BOOL finished) {
            self.statusBarHidden = YES;
            [self setNeedsStatusBarAppearanceUpdate];
            [self setupScrollViewDataWithMainScreenSize:[UIScreen mainScreen].bounds.size];
            [tempImageView removeFromSuperview];
        }];
    } else {
        [self setupScrollViewDataWithMainScreenSize:[UIScreen mainScreen].bounds.size];
        self.statusBarHidden = YES;
        [self setNeedsStatusBarAppearanceUpdate];
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupSubviews];
//    [self setupScrollViewDataWithMainScreenSize:[UIScreen mainScreen].bounds.size];
}

- (BOOL)prefersStatusBarHidden {
    return self.statusBarHidden;
}

/**
 *  支持的屏幕方向
 */
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

/**
 *  默认的屏幕方向
 */
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationUnknown;
}

// Notifies when rotation begins, reaches halfway point and ends.
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
//    NSLog(@"will");
}



- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
//    NSLog(@"did");
}

/*
 NS_AVAILABLE_IOS(8_0)
 
 When the content container forwards viewWillTransitionToSize:withTransitionCoordinator: to its children, it will call this method to determine what size to send them.
 
 If the returned size is the same as the child container's current size, viewWillTransitionToSize:withTransitionCoordinator: will not be called.
 */
//- (CGSize)sizeForChildContentContainer:(id <UIContentContainer>)container withParentContainerSize:(CGSize)parentSize {
//    
//}

/*
 NS_AVAILABLE_IOS(8_0);
 This method is called when the view controller's view's size is changed by its parent (i.e. for the root view controller when its window rotates or is resized).
 
 If you override this method, you should either call super to propagate the change to children or manually forward the change to children.
 */
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator {

    self.isViewTransition = YES;
    
    //self.scrollView.hidden = YES;
    UIImageView *currentImageView = [self.scrollView.subviews objectAtIndex:self.currentIndex];
    UIImageView *tempImageView = [[UIImageView alloc] init];
    tempImageView.image = currentImageView.image;
    tempImageView.frame = currentImageView.bounds;
    tempImageView.center = self.view.center;
    [self.view addSubview:tempImageView];
    [self.scrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    
    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        tempImageView.bounds = [self getImageShowFrame:tempImageView.image mainScreenSize:size];
        tempImageView.center = self.view.center;
    } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        [self setupScrollViewDataWithMainScreenSize:size];
        [tempImageView removeFromSuperview];
        self.isViewTransition = NO;
    }];
}

/*
  NS_AVAILABLE_IOS(8_0);
 This method is called when the view controller's trait collection is changed by its parent.
 
 If you override this method, you should either call super to propagate the change to children or manually forward the change to children.
 */
- (void)willTransitionToTraitCollection:(UITraitCollection *)newCollection withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator {
    
}


#pragma mark - 初始化
- (void)setupSubviews {
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.pagingEnabled = YES;
    scrollView.backgroundColor = [UIColor blackColor];
    scrollView.hidden = YES;
    scrollView.delegate = self;
    [self.view addSubview:scrollView];
    self.scrollView = scrollView;
    
    // 添加手势
    UITapGestureRecognizer *onceTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onceTapOnScrollView)];
    onceTapGestureRecognizer.numberOfTapsRequired = 1;
    
    UITapGestureRecognizer *twiceTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(twiceTapGestureRecognizer)];
    twiceTapGestureRecognizer.numberOfTapsRequired = 2;
    
    [onceTapGestureRecognizer requireGestureRecognizerToFail:twiceTapGestureRecognizer];
    
    [self.scrollView addGestureRecognizer:onceTapGestureRecognizer];
    [self.scrollView addGestureRecognizer:twiceTapGestureRecognizer];
    
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.view.mas_bottom);
        make.left.equalTo(self.view.mas_left).mas_offset(-ImageViewMargin / 2);
        make.right.equalTo(self.view.mas_right).mas_offset(ImageViewMargin / 2);
    }];
}

- (void)setupScrollViewDataWithMainScreenSize:(CGSize)mainScreenSize {
#warning TODO
    [self.scrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    
    
    NSInteger numberOfImageView = 0;
    if ([self.delegate respondsToSelector:@selector(numberOfPhotoBrowser:)]) {
        numberOfImageView = [self.delegate numberOfPhotoBrowser:self];
    }
    if (numberOfImageView  == 0) {
        return;
    }

    self.scrollView.hidden = NO;
    for (NSInteger index = 0; index < numberOfImageView; index++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.bounds = self.beginningImageView.bounds;

        UIImage *originalImage = [self originalImageAtIndex:index];
        if (originalImage) {
            imageView.image = originalImage;
            imageView.bounds = [self getImageShowFrame:originalImage mainScreenSize:mainScreenSize];
        } else {
            imageView.bounds = self.beginningImageView.frame;
            [imageView sd_setImageWithURL:[NSURL URLWithString:[self originalImageURLStringAtIndex:index]] placeholderImage:[self thumbnailImageAtIndex:index] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                if (error) {
                    
                } else {
                    CGRect showFrame = [self getImageShowFrame:image mainScreenSize:mainScreenSize];
                    [UIView animateWithDuration:AnimateWithDuration animations:^{
                        imageView.bounds = showFrame;
                    }];
                }
            }];
        }
        
        imageView.center = CGPointMake((mainScreenSize.width + ImageViewMargin) * (index + 1 / 2.0), mainScreenSize.height / 2);
        [self.scrollView addSubview:imageView];
    }
    
    CGPoint contentOffset = CGPointMake((mainScreenSize.width + ImageViewMargin) * self.currentIndex, 0);
    NSLog(@"currentIndex 1 : %zd",  self.currentIndex);
    // 设置 scrollView 的时候，会触发 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
    self.scrollView.contentSize = CGSizeMake((mainScreenSize.width + ImageViewMargin) * numberOfImageView, 0);
    //NSLog(@"width : %f", (mainScreenSize.width + ImageViewMargin) * self.currentIndex);
    NSLog(@"currentIndex 2 : %zd",  self.currentIndex);
    [self.scrollView setContentOffset:contentOffset animated:NO];
    NSLog(@"currentIndex 3 : %zd",  self.currentIndex);
    
}

#pragma mark - other

- (void)onceTapOnScrollView {
    self.statusBarHidden = NO;
    [self setNeedsStatusBarAppearanceUpdate];
//    [self.navigationController popViewControllerAnimated:NO];
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void)twiceTapGestureRecognizer {
    NSLog(@"twice");
}


- (CGRect)getImageShowFrame:(UIImage *)image mainScreenSize:(CGSize)mainScreenSize {
    CGFloat imageWidth = image.size.width;
    CGFloat imageHeight = image.size.height;
    
    
    // 铺满窄的边
    if (mainScreenSize.width > mainScreenSize.height) { // 横屏
        imageWidth = (imageWidth / imageHeight) * mainScreenSize.height;
        imageHeight = mainScreenSize.height;
    } else {
        imageHeight = (imageHeight / imageWidth) * mainScreenSize.width;
        imageWidth = mainScreenSize.width;
    }
    return CGRectMake((mainScreenSize.width - imageWidth) / 2, (mainScreenSize.height - imageHeight) / 2, imageWidth, imageHeight);
}


- (UIImage *)thumbnailImageAtIndex:(NSInteger)index {
    NSString *URLString = [self thumbnailImageURLStringAtIndex:index];
    if (URLString) {
        return [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:URLString];
    }
    return nil;
}

- (NSString *)thumbnailImageURLStringAtIndex:(NSInteger)index {
    if ([self.delegate respondsToSelector:@selector(photoBrowser:thumbnailURLStringAtIndex:)]) {
        return [self.delegate photoBrowser:self thumbnailURLStringAtIndex:index];
    }
    return nil;
}

- (UIImage *)originalImageAtIndex:(NSInteger)index {
    NSString *URLString = [self originalImageURLStringAtIndex:index];
    if (URLString) {
        return [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:URLString];
    }
    
    return nil;
}

- (NSString *)originalImageURLStringAtIndex:(NSInteger)index {
    if ([self.delegate respondsToSelector:@selector(photoBrowser:originalURLStringAtIndex:)]) {
        return [self.delegate photoBrowser:self originalURLStringAtIndex:index];
    }
    return nil;
}

#pragma mark - ScrollView
/**
 *  屏幕翻转时，scrollview 的
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (!self.isViewTransition) {
        //    NSLog(@"content : %@ ", NSStringFromCGSize(scrollView.contentSize));
        //    NSLog(@"scrollView.contentOffset.x = %f", scrollView.contentOffset.x);
        //    NSLog(@"scrollView.bounds.size.width = %f", scrollView.bounds.size.width);
        self.currentIndex = (scrollView.contentOffset.x + scrollView.bounds.size.width / 2) / scrollView.bounds.size.width;
    }
    
}

// called on finger up if the user dragged. decelerate is true if it will continue moving afterwards
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {

    NSLog(@"currentIndex = %zd",  self.currentIndex );
}



@end
